<?php

namespace app\cps\service;

use app\model\Link;
use app\model\User;
use app\model\PayRecord;
use think\facade\Db;
use app\common\Common;
use app\common\Error;
use think\facade\Cache;
use app\model\DailyDeliveryData;
use app\model\Videos;
use app\model\ResponsibilityPerson;
use app\model\LaunchAccount;
use app\model\OfficialAccounts;
use app\cps\controller\OpenDouyin;
class CostInfoService
{

    private $model;
    private $userModel;
    private $payRecordModel;
    private $dailyDeliveryDataModel;
    private $videosModel;
    private $launchAccountModel;
    private $responsibilityPersonModel;
    private $officialaccountsModel;
    public function __construct(Link $model, User $userModel, PayRecord $payRecordModel, DailyDeliveryData $dailyDeliveryDataModel, Videos $videosModel, ResponsibilityPerson $responsibilityPersonModel, LaunchAccount $launchAccountModel,OfficialAccounts $officialaccountsModel)
    {
        $this->model = $model;
        $this->userModel = $userModel;
        $this->payRecordModel = $payRecordModel;
        $this->dailyDeliveryDataModel = $dailyDeliveryDataModel;
        $this->videosModel = $videosModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->launchAccountModel = $launchAccountModel;
        $this->officialaccountsModel = $officialaccountsModel;
    }
    //抖音巨量详情时间段数据
    public function getTiktokAdvData($params,$userInfo){
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);
        if(empty($params['advertiser_id'])||empty($params['company_id'])){
            return ['message'=> '数据错误'];
        }
        $opendouyin=new OpenDouyin();
        $company_id=$params['company_id'];
        $advertiser_id=$params['advertiser_id'];
        $link_id=$params['link_id'];
        $linkWhere = [['link_switch', '=', 1], ['media_id', '=', 1],['id', '=', $link_id]];
        $linkData = $this->model->getInfoByWhere($linkWhere, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate, subject_id,official_account_id');
        $openlist=$opendouyin::getStatisticsList($company_id,$advertiser_id);
        if($openlist['code']!=200){
            //判断链接中的公众号id是否存在
            if(!empty($linkData['official_account_id'])){
                $officialFind=$this->officialaccountsModel->getInfoById($linkData['official_account_id'],'company_id');
                //判断公众号是否存在
                if(!empty($officialFind)){
                    //获取数据
                    $company_id=$officialFind['company_id'];
                    $openlist=$opendouyin::getStatisticsList($company_id,$advertiser_id);
                    if($openlist['code']!=200){
                        return ['message'=> '暂无数据'];
                    }
                }else{
                    return ['message'=> '暂无数据'];
                }
                
            }else{
                return ['message'=> '暂无数据'];
            }
            
        }
        //获得每个时间点的实际数据
        $opendata=$openlist['data'];
        $data=[];
  
        
        $ids = $link_id;
        //循环计算每个实际时间段的实际消耗，新充人数，新充笔数，收益，利润
        foreach($opendata['stats'] as $key=>$val){
            //时间段
            $data[$key]['stat_time']=$val['stat_time_hour'];
            //消耗
            $data[$key]['stat_cost']=$val['metrics']['stat_cost'];
            //实际消耗
            $actualCost = 0;
            if (!empty($linkData['rebate'])) {
                $actualCost = round($data[$key]['stat_cost']  / ($linkData['rebate'] / 100 + 1), 2);
            }
            $data[$key]['reality_cost']=$actualCost;
            //新充人数(每小时段的人数)
            $times=explode(' - ',$val['stat_time_hour']);
            $time2 = explode(' ',$times[0]);
            $newUserNumber=$this->userModel->whereBetween('activation_time',[$times[0],$time2[0].' '.$times[1]])->where('link_id',$ids)->count();
       
            $data[$key]['new_user_number'] = $newUserNumber;
            //充值笔数
            $where=[];
            $where[]=['status','=',1];
            $where[]=['link_id','=',$ids];
            $where[]=['pay_time','between',[strtotime($times[0]),strtotime($time2[0].' '.$times[1])]];
            $payData = $this->payRecordModel->getInfo($where, 'link_id, uid, total_fee, activation_time');
            $uids=array_column($payData, 'uid');

            $data[$key]['new_recharge_number'] = count($payData);
            //充值人数
            $newUserPayNumber=0;
            $data[$key]['new_user_pay_number'] = $newUserPayNumber;
            if( $data[$key]['new_recharge_number']>0){
                $newUserPayNumber=$this->userModel->whereIn('id',$uids)->count();
       
                $data[$key]['new_user_pay_number'] = $newUserPayNumber;
            }
          
            //人均次数
            $data[$key]['percapita_number'] =  $newUserPayNumber == 0||count($payData)==0 ? 0 : round($newUserPayNumber / count($payData), 2);
            //当前总充值
           
            $current =array_column($payData,'total_fee');
            $currentRecharge=array_sum($current);
            $data[$key]['current_recharge'] =round($currentRecharge, 2);
            //转化成本
            $data[$key]['conversion_cost'] =  $newUserPayNumber == 0 ||$actualCost==0? 0 : round($actualCost / $newUserPayNumber, 2);
            //收益
            $currentRechargeDiscount = round($currentRecharge * 0.9, 2); // 当期95充值;
            $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
            //净利润
            $data[$key]['current_recharge_profit'] = $actualCost == 0||$currentRechargeDiscount==0 ? 0 : round($currentRechargeDiscount - $actualCost, 2);
            //返后ROI
            $data[$key]['actual_recovery'] = $actualCost == 0 ||$currentRechargeDiscount==0? 0 : round($currentRechargeDiscount / $actualCost * 100, 2) . '%';
            //复充率
            $total_count = count($uids);
            $unique_count=count(array_unique($uids));
            $m_num=$total_count-$unique_count;
            $data[$key]['recharging_rate'] =  $m_num == 0||$total_count==0 ? 0 :round($m_num/$total_count*100,2).'%';
        }
        return array_reverse($data);
    }
        
}